let stu_data;
$(document).ready(function () {
    // 执行页面加载时获取学生列表
    getStudentList();
    // 监听添加学生信息表单提交事件
    $('.box1').submit(function (event) {
        event.preventDefault();
        addStudentInfo();
    });
    // 监听修改学生信息表单提交事件
    $('.box2').submit(function (event) {
        event.preventDefault();
        let id = $('table .btn-danger').closest('tr').find('td:eq(0)').text();
        // console.log(id);
        confirmEdit(id);
    });

    // 监听编辑按钮点击事件
    $('table').on('click', '.btn-primary', function () {
        let id = $(this).closest('tr').find('td:eq(0)').text();
        editStudentInfo(id);
    });

    // 监听删除按钮点击事件
    $('table').on('click', '.btn-danger', function () {
        let id = $(this).closest('tr').find('td:eq(0)').text();
        deleteStudentInfo(id);
    });
    //监听清空学生表点击事件
    $('.tool').click(function () {
        clearStudent();
    });

    // 取消按钮事件
    $('.btn-cel').on('click', function (){
        $('.box1').css('visibility', 'visible');
        $('.box2').css('visibility', 'hidden');
        $('.input-box-wrapper').css('flex-direction','row');
    });

    //监听搜索事件
    $('#search-button').on('click', function () {
        const keyName = $('#search-input').val();
        performSearch(keyName);
    });
});

// 获取学生列表
function getStudentList() {
    $.ajax({
        url: "../api.php/get_student_info",
        type: "GET",
        dataType: "json",
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                displayStudentList(res["data"]);
            }
        },
        error: function () {
            alert('出错了');
        }
    });
}

// 显示学生列表
function displayStudentList(data) {
    $('table tbody').empty();
    data.forEach(function (data) {
        $('table tbody').append(`
             <tr>
                  <td>${data.student_id}</td>
                  <td>${data.student_name}</td>
                  <td>${data.description}</td>
                  <td>${data.student_sex}</td>
                  <td>
                       <button type="button" class="btn btn-sm btn-primary">修改</button>
                       <button type="button" class="btn btn-sm btn-danger">删除</button>
                  </td>
             </tr>
        `);
    });

}


// 添加学生信息
function addStudentInfo() {
    var student = {
        student_id: $('#id').val(),
        student_name: $('#name').val(),
        student_sex: $('#gender').val(),
    };
    if (!student.student_id) {
        alert('ID为空');
        return;
    } else if (!student.student_name) {
        alert('姓名为空');
        return;
    } else if (!student.student_sex) {
        alert('性别为空');
        return;
    }
    $.ajax({
        url: "../api.php/get_student_info",
        type: "GET",
        dataType: "json",
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                if (res["data"].findIndex(n => n.student_id == student.student_id) != -1) {
                    alert('学号已经存在！');
                } else {
                    $.ajax({
                        url: "../api.php/add_student",
                        type: "POST",
                        dataType: "json",
                        data:{'student_id':student.student_id, 'student_name':student.student_name, 'student_sex':student.student_sex},
                        success: function (res) {
                            console.log('register', res);
                            if (res["code"] === 200) {
                                alert('成功添加学生信息！');
                                getStudentList();
                                $('.box1 form')[0].reset();
                            }
                        },
                        error: function () {
                            alert('出错了');
                        }
                    });
                }
            }
        },
        error: function () {
            alert('出错了');
        }
    });


}
//传入初值函数
function setData(data) {
    $('#newId').val(data.student_id);
    $('#newName').val(data.student_name);
    $('#newGender').val(data.student_sex);
}
//搜索逻辑
function performSearch(keyName) {

    $.ajax({
        url: "../api.php/get_student_info",
        type: "GET",
        dataType: "json",
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                if (!keyName) {
                    getStudentList();
                } else {
                    let student = res["data"].find(student => student.student_name === keyName);
                    // console.log('1', student.student_id);
                    // console.log('2', student.student_name);
                    // console.log('3', student.description);
                    // console.log('4', student.student_sex);
                    $('table tbody').empty();
                    $('table tbody').append(`
                      <tr>
                        <td>${student.student_id}</td>
                        <td>${student.student_name}</td>
                        <td>${student.description}</td>
                        <td>${student.student_sex}</td>
                        <td>
                          <button type="button" class="btn btn-sm btn-primary">修改</button>
                          <button type="button" class="btn btn-sm btn-danger">删除</button>
                        </td>
                      </tr>
                    `);

                }
            }
        },
        error: function () {
            alert('出错了');
        }
    });

}
// 编辑学生信息
let needEditIndex = -1;
function editStudentInfo(id) {
    $.ajax({
        url: "../api.php/get_student_info",
        type: "GET",
        dataType: "json",
        success: function (res) {
            console.log('register', res);
            if (res["code"] === 200) {
                needEditIndex = res["data"].findIndex(student => student.student_id === id);
                localStorage.setItem("stu_grades", JSON.stringify(res["data"]));
                try {
                    stu_data = JSON.parse(localStorage.getItem("stu_grades"));
                } catch (e) {
                    console.log(e);
                }
                document.getElementById("newName").value = stu_data[needEditIndex].student_name;
            }
        },
        error: function () {
            alert('出错了');
        }
    });
    getStudentList();
    $('.box1').css('visibility', 'hidden');
    $('.box2').css('visibility', 'visible');
    $('.input-box-wrapper').css('flex-direction','row-reverse');

}
//确认修改
function confirmEdit(id) {
    let student = {
        student_name: $('#newName').val(),
        student_sex: $('#newGender').val()
    };
    $.ajax({
        url: "../api.php/get_student_info",
        type: "GET",
        dataType: "json",
        success: function (res) {
            if (res["code"] === 200) {
                let data = res.data;
                // student.student_id = data[needEditIndex].student_id;
                // student.student_name = data[needEditIndex].student_name;
                // student.student_sex = data[needEditIndex].student_sex;
                // student.description = data[needEditIndex].description;
                if (!student.student_name) {
                    alert('姓名为空');
                    return;
                } else if (!student.student_sex) {
                    alert('性别为空');
                    return;
                }
                $.ajax({
                    url: "../api.php/update_student_info",
                    type: "POST",
                    dataType: "json",
                    data: {'student_id': data[needEditIndex].student_id,'student_name': student.student_name, 'student_sex': student.student_sex, 'description':data[needEditIndex].description},
                    success: function (res) {
                        console.log('confirm', res);
                        // console.log(data[needEditIndex].student_id)
                        // console.log(student.student_name);
                        // console.log(student.student_sex);
                        // console.log(data[needEditIndex].description);
                        if (res["code"] === 200) {
                            alert('成功修改学生信息！');
                            location.reload();
                        }
                    },
                    error: function () {
                        alert('出错了');
                    }
                });

                getStudentList();
                $('.box1').css('visibility', 'visible');
                $('.box2').css('visibility', 'hidden');
                $('.input-box-wrapper').css('flex-direction','row');
            }
        },
        error: function () {
            alert('出错了');
        }
    });






}

// 删除学生信息
function deleteStudentInfo(id) {

    $.ajax({
        url: "../api.php/delete_student",
        type: "POST",
        dataType: "json",
        data: {'student_id': id},
        success: function (res) {
            console.log('register', res);

            if (res["code"] === 200) {
                // const index = res["data"].findIndex(student => student.student_id == id);

                alert('成功删除该学生！');
                getStudentList();
            }
        },
        error: function () {
            alert('出错了');
        }
    });


}

//清空数据
function clearStudent() {
    document.getElementById("id").value = "";
    document.getElementById("name").value = "";
    document.getElementById("description").value = "";

    // alert('数据清除成功！');
    // location.reload();
}
